import api from "@/api/index";
import {
  setToken,
  setAccessUser,
  delToken,
  delAccessUser,
  delShareToken,
  getAccessUser,
} from "@/auth/auth";
import { constantRouter, asyncRouter,anyRouter } from "@/router/routes";
function filterAsyncRouter(arr1, arr2) {
  let result = [];
  function findChildren(obj) {
    if (obj.children) {
      obj.children = obj.children.filter((child) => {
        if (child.meta && child.meta.permission) {
          let permissions = child.meta.permission.split("|");
          if (permissions.some((permission) => arr2.includes(permission))) {
            return true;
          }
        }
        return false;
      });
      obj.children.forEach((child) => findChildren(child));
    }
  }

  arr1.forEach((item) => {
    if (item.meta && item.meta.permission) {
      let permissions = item.meta.permission.split("|");
      if (permissions.some((permission) => arr2.includes(permission))) {
        let newItem = { ...item };
        findChildren(newItem);
        result.push(newItem);
      }
    }
  });

  return result;
}

function extractAndDistinctPrefix(arr) {
  const prefixSet = new Set();
  arr.forEach((item) => {
    const prefix = item.split(":")[0];
    prefixSet.add(prefix);
  });
  return Array.from(prefixSet);
}
const state = {
  token: "", // 登录后的token
  loginName: "", //
  authorities: [],
  menuList: [...constantRouter,...asyncRouter,...anyRouter],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_LOGINNAME: (state, loginName) => {
    state.loginName = loginName;
  },
  SET_AUTHORITIES: (state, authorities) => {
    state.authorities = authorities;
  },
  // setPermission: (state) => {
  //   let authorities = getAccessUser("AJReportUser").authorities;
  //   let routeList = extractAndDistinctPrefix(authorities);
  //   let asyncRouters = JSON.parse(JSON.stringify(asyncRouter));
  //   let route = filterAsyncRouter(asyncRouters, routeList);
  //   let menuList = [...constantRouter, ...route,...anyRouter];
  //   state.menuList = menuList;
  // },
};

const actions = {
  // 登录
  async Login({ commit }, userInfo) {
    // const { code, data,message } = await api.login.getUserList(userInfo);
    // if (code != "200") return message;
    // if(code=="")
    // commit("SET_TOKEN", data.token);
    // commit("SET_LOGINNAME", data.loginName);
    // commit("SET_AUTHORITIES", data.authorities);
    // setToken(data.token);
    setAccessUser('ffffff');
    return "ok";
  },

  // 登出
  async LogOut({ commit, state }) {
    // await api.login.logout();
    commit("SET_TOKEN", "");
    commit("SET_LOGINNAME", "");
    commit("SET_AUTHORITies", []);
    delToken();
    delShareToken();
    delAccessUser();
    return "ok";
  },
};

//更改密码

const getters = {
  // 你的 getters
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
